package fr.labri.macchiato.framework.technical.queryLauncher;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.labri.macchiato.framework.business.finder.Callback;

/**
 * Sends a sparql query to a distant server via the REST protocol
 * 
 * @author Paul Sarraute
 * 
 */
public class RestQueryLauncher implements QueryLauncher {

	private final static String BASE_URL = "http://macchiato.fr/Auchan/sparql";
	private final static String ACCEPT_JSON = "application/sparql-results+json";

	private RequestBuilder requestBuilder;
	private String queryResult;

	/**
	 * 
	 */
	public RestQueryLauncher() {
		requestBuilder = new RequestBuilder(RequestBuilder.POST, BASE_URL);
		requestBuilder.setHeader("Content-Type",
				"application/x-www-form-urlencoded");
	}

	private void sendQuery(String query, final Callback<String> callback)
			throws RequestException {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("query=").append(query);

		queryResult = null;
		requestBuilder.sendRequest(stringBuilder.toString(),
				new RequestCallback() {
					@Override
					public void onResponseReceived(Request request,
							Response response) {
						queryResult = response.getText();
						callback.onCallback(queryResult);
					}

					@Override
					public void onError(Request request, Throwable exception) {
						exception.printStackTrace();
					}
				});
	}

	@Override
	public void launchQueryForJSON(String query,
			final AsyncCallback<String> callback) {
		requestBuilder.setHeader("Accept", ACCEPT_JSON);

		try {
			sendQuery(query, new Callback<String>() {

				@Override
				public void onCallback(String result) {
					callback.onSuccess(result);

				}
			});
		} catch (RequestException e) {

			callback.onFailure(e);
		}
	}

}
